import { login, logout } from "@/api/login";
import { getToken, setToken, setWebApiToken, removeToken ,setUserToken,removeUserToken,setUserInfo,setPermissions,removeUserInfo,removePermissions} from "@/utils/auth";
import md5 from 'js-md5'

const user = {
  state: {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    permissions: {},
    userInfo:{}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = md5(userInfo.password);
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login({ username, password, code, uuid})
          .then((res) => {
            // gateway的
            setToken(res.data.token);
            setUserToken(res.data.token)
            setPermissions(JSON.stringify(res.data.permissions));
            setUserInfo(JSON.stringify(res.data.user));
            // web-api 的
            setWebApiToken("Authorization-web-api", res.data.token);
           
            commit("SET_TOKEN", res.data.token);
            localStorage.setItem("user",res.data.user)
            const user = res.data.user;
            commit("SET_USERINFO", user);
            if (res.data.permissions) {
              console.log("set permissions",res.data.permissions)
              commit("SET_PERMISSIONS", res.data.permissions);
            } else {
              //commit("SET_ROLES", ["ROLE_DEFAULT"]);
            }
            commit("SET_NAME", user.username);
            // commit("SET_AVATAR", avatar);
            resolve(res);
            
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit("SET_TOKEN", "");
        removeToken();
        removeUserToken()
        removePermissions();
        removeUserInfo();
        resolve();
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        removeToken();
        removeUserToken()
        resolve();
      });
    },
  },
};

export default user;
